<template>
  <div>
    <x-card v-if="hasPerm('classdynamic:page')">
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="6" :sm="24">
                <a-form-item label="关键词">
                 <a-input v-model="queryParam.ContentKey" allow-clear placeholder="请输入关键词"/>
                </a-form-item>
            </a-col>
            
            <a-col :md="6" :sm="24">
                <a-form-item label="班级">
                  <a-select allowClear v-model="queryParam.ClassId" placeholder="请选择班级">
                    <a-select-option v-for="item in classList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
            </a-col>
            <a-col  :md="6" :sm="24">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :rowKey="(record) => record.id"
        :rowSelection="options.rowSelection"
      >
        <template slot="operator" v-if="hasPerm('classdynamic:add')">
          <a-button @click="$refs.addForm.add(myAuthClassList)" icon="plus" type="primary" v-if="hasPerm('classdynamic:add')">发布动态</a-button>
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('classdynamic:delete')" @click="batchDelete"><a-icon type="delete"/>批量删除</a-button>
          <x-down
            style="display:none"
            v-if="hasPerm('classdynamic:export')"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <span slot="content" slot-scope="text, record">
          <span slot="content" >
            <p style="width:200px;height:40px;overflow:hidden;">{{record.content}}</p>
          </span>
        </span>
        <span slot="cRoomState" slot-scope="text, record">
          <span slot="cRoomState" >
            <a-switch v-model="record.cRoomState" @change="changeStatus(record)" />
          </span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('classdynamic:edit')" @click="showImages(record)">预览图片</a>
          <a-divider type="vertical" v-if="hasPerm('classdynamic:edit') & hasPerm('classdynamic:delete')"/>
          <a v-if="hasPerm('classdynamic:edit')" @click="$refs.leaveMsg.show(record)">查看留言</a>
          <a-divider type="vertical" v-if="hasPerm('classdynamic:edit') & hasPerm('classdynamic:shield')"/>
          <a-popconfirm v-if="hasPerm('classdynamic:shield')" placement="topRight" title="确认屏蔽？" @confirm="() => pingbi(record)">
            <a>屏蔽</a>
          </a-popconfirm>
          <a-divider type="vertical" v-if="hasPerm('classdynamic:edit') & hasPerm('classdynamic:delete')"/>
          <a-popconfirm v-if="hasPerm('classdynamic:delete')" placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <add-form ref="addForm" @ok="handleOk" />
      <edit-form ref="editForm" @ok="handleOk" />
    </a-card>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handlePreviewCancel">
              <img class="img-item" v-for="(item, index) in imgList" :key="index" :src="item" alt="">
            </a-modal>
    <leave-msg ref="leaveMsg"></leave-msg>
  </div>
</template>

<script>
import { STable, XCard, XDown } from '@/components';
import { sysPosList, } from '@/api/modular/garden/classManage';
import { classDynamicPage, classDynamicDelete, getMyAuthClassList, classDynamicChangeStatus } from '@/api/modular/garden/classDynamicApi';
import addForm from './addForm';
import editForm from './editForm';
import leaveMsg from './leaveMsg'

export default {
  components: {
    XDown,
    XCard,
    STable,
    addForm,
    editForm,
    leaveMsg,
  },

  data () {
    return {
      // 查询参数
      queryParam: {
        ContentKey: '',
        ClassId: '',
      },
      // 表头
      columns: [
        {
          title: '动态内容',
          dataIndex: 'content',
          scopedSlots: { customRender: 'content' }
        },
        {
          title: '班级',
          dataIndex: 'classNames'
        },
        {
          title: '发布人',
          dataIndex: 'createUserName',
        },
        {
          title: '发布时间',
          dataIndex: 'createdTime',
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return classDynamicPage(Object.assign(parameter, this.queryParam)).then((res) => {
          if(res.data.rows.length){
            res.data.rows.forEach(item => {
              item.classNames = '';
              item.classList.forEach(cls => {
                item.classNames = item.classNames + ' ' + cls.className;
              })
            })
          }
          console.log(res.data)
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      classList: [],
      myAuthClassList: [],
      previewVisible: false,
      imgList: [],
      imgTitle: '',
    }
  },

  created () {
    if (this.hasPerm('classdynamic:edit') || this.hasPerm('classdynamic:delete')) {
      this.columns.push({
        title: '操作',
        width: '300px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  mounted(){
    this.imgTitle = process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/previewImg?id=';
    this.getClass();
    this.getMyAuthClassList();
  },

  methods: {
      getMyAuthClassList(){
        getMyAuthClassList().then((res) => {
          this.myAuthClassList = res.data;
        })
      },
      getClass(){
        let obj = {
          isArchived: false
        }
        sysPosList(obj).then((res) => {
          this.classList = res.data;
        })
      },
    /**
     * 单个删除
     */
    singleDelete (record) {
      const param = [ record.id ]
      this.sysPosDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete () {
      const paramIds = this.selectedRowKeys.map((d) => {
        return d
      })
      this.sysPosDelete(paramIds)
    },
    /**
     * 删除
     */
    sysPosDelete (param) {
      classDynamicDelete(param).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.clearRefreshSelected()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    changeStatus (record) {
      console.log(record)
    },
    /**
     * 批量导出
     */
    batchExport () {
      // const paramIds = this.selectedRowKeys.map((d) => {
      //   return { 'id': d }
      // })
      // sysPosExport(paramIds).then((res) => {
      //   this.$refs.batchExport.downloadfile(res)
      // })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    pingbi(record){
      let state = record.state == 1?2:1;
      classDynamicChangeStatus(null,'/ClassDynamic/ChangeStatus?Id='+record.id+'&Status='+state).then(res => {
        if(res.success){
          this.$message.success('更改成功');
        }else{
          this.$message.error('更改失败：' + res.message)
        }
      })
    },
    handlePreviewCancel(){
      this.previewVisible = false;
    },
    showImages(record){
      let _imgs = record.images;
      this.imgList = _imgs.map(item => {
        return this.imgTitle + item.filedId;
      })
      this.previewVisible = true;
    },
  }

}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.img-item{
  width: 160px;
}
</style>
